package org.jeecg.modules.business.transfer.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.entity.WmsBasicMaterialStockInfo;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.material.service.IWmsBasicMaterialStockInfoService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseService;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.business.transfer.entity.PaperWarning;
import org.jeecg.modules.business.transfer.entity.vo.PaperWarningParam;
import org.jeecg.modules.business.transfer.mapper.PaperWarningMapper;
import org.jeecg.modules.business.transfer.service.IPaperWarningService;
import org.jeecg.modules.utils.dto.SmsDto;
import org.jeecg.modules.utils.service.IAlertService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 纸筒库存预警信息
 * @Author: jeecg-boot
 * @Date:   2023-11-10
 * @Version: V1.0
 */
@Service
@Slf4j
public class PaperWarningServiceImpl extends ServiceImpl<PaperWarningMapper, PaperWarning> implements IPaperWarningService {

    private static final String MATERIAL_CODE = "ZT001";    // 纸筒物料code
    private static final String WAREHOUSE_CODE = "CK-379";  // 四期纸筒仓code
    private static final String TEMPLATE_CODE = "paper-warning";    // 告警规则code

    @Autowired
    private PaperWarningMapper paperWarningMapper;

    @Autowired
    private IBasicMaterialService basicMaterialService;

    @Autowired
    private IWmsBasicWarehouseService warehouseService;

    @Autowired
    private IWmsRepertoryService repertoryService;

    @Autowired
    private IAlertService alertService;

    @Autowired
    private IWmsBasicMaterialStockInfoService materialStockInfoService;

    /**
     * 分页
     * @param page
     * @param param
     * @return
     */
    @Override
    public Page<PaperWarning> pageList(Page<PaperWarning> page, PaperWarningParam param) {
        List<PaperWarning> list = paperWarningMapper.pageList(page, param);
        return page.setRecords(list);
    }

    /**
     * 批量关闭
     * @param ids
     */
    @Override
    public void batchClose(List<String> ids) {
        List<PaperWarning> list = this.listByIds(ids);
        if (list.stream().anyMatch(a -> !"1".equals(a.getStatus()))) {
            throw new JeecgBootException("只有状态是未处理的才能关闭！");
        }
        this.update(new LambdaUpdateWrapper<PaperWarning>()
                .in(PaperWarning::getId, ids)
                .set(PaperWarning::getStatus, "3"));
    }

    /**
     * 校验条料仓安全库存
     */
    @Override
    public void checkSafeInventory(){
        BasicMaterial material = basicMaterialService.getOne(new LambdaQueryWrapper<BasicMaterial>()
                .eq(BasicMaterial::getCode, MATERIAL_CODE)
                .last("limit 1"));
        if (material == null) {
            return;
        }
        List<WmsBasicMaterialStockInfo> list = materialStockInfoService.list(new LambdaQueryWrapper<WmsBasicMaterialStockInfo>()
                .eq(WmsBasicMaterialStockInfo::getWmsBasicMaterialId, material.getId()));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        if (list.get(0).getSafeInventory() == null) {
            return;
        }

        WmsBasicWarehouse warehouse = warehouseService.getOne(new LambdaQueryWrapper<WmsBasicWarehouse>()
                .eq(WmsBasicWarehouse::getCode, WAREHOUSE_CODE)
                .last("limit 1"));
        if (warehouse == null) {
            return;
        }

        List<WmsRepertory> repertoryList = repertoryService.list(new LambdaQueryWrapper<WmsRepertory>()
                .eq(WmsRepertory::getWmsBasicWarehouseId, warehouse.getId())
                .eq(WmsRepertory::getMaterialId, material.getId()));
        for (WmsRepertory repertory : repertoryList) {
            try {
                SmsDto smsDto = new SmsDto();
                Map<String, Object> data = new HashMap<>();
                data.put("materialCode", material.getCode());
                data.put("warehouseName", warehouse.getName());
                data.put("stockQuantity", repertory.getStockQuantity());
                data.put("safeInventory", list.get(0).getSafeInventory());
                if (repertory.getStockQuantity() != null) {
                    BigDecimal safe = list.get(0).getSafeInventory();
                    if (repertory.getStockQuantity().compareTo(safe) == -1) {
                        // 生成纸筒库存预警信息
                        PaperWarning paperWarning = new PaperWarning();
                        paperWarning.setMaterialId(material.getId());
                        paperWarning.setStatus("1");
                        paperWarning.setStockQuantity(NumberUtil.toStr(repertory.getStockQuantity()));
                        paperWarning.setWarehouseId(warehouse.getId());
                        paperWarning.setWarehouseAreaId(repertory.getWmsBasicWarehouseAreaId());
                        paperWarning.setWarningTime(new Date());
                        paperWarning.setSafeInventory(NumberUtil.toStr(list.get(0).getSafeInventory()));
                        paperWarning.setMaxInventory(NumberUtil.toStr(list.get(0).getMaxInventory()));
                        paperWarning.setDelFlag("0");
                        this.save(paperWarning);
                        // 发送消息
                        this.send(smsDto, TEMPLATE_CODE, data);
                        continue;
                    }
                }
                this.inactive(smsDto, TEMPLATE_CODE, data);
            } catch (Exception e) {
                log.error("纸筒库存预警定时任务出错", e);
            }
        }
    }

    //发预警消息
    private void send(SmsDto smsDto, String template, Map<String, Object> data) throws Exception {
        smsDto.setTemplateCode(template);
        smsDto.setData(data);
        alertService.send(smsDto);
    }

    //取消预警
    private void inactive(SmsDto smsDto, String template, Map<String, Object> data) throws Exception {
        smsDto.setTemplateCode(template);
        smsDto.setData(data);
        alertService.inActive(smsDto);
    }
}
